package pair.parking.action;

import pair.parking.bean.Car;
import pair.parking.bean.CarTicket;
import pair.parking.bean.ParkingLot;
import pair.parking.common.CommonData;

import java.util.HashSet;
import java.util.Set;
import java.util.UUID;

/**
 * Create by Vic Xu on 8/24/2018
 *
 * @author Vic Xu
 */
public abstract class BaseParkingBoy {

    public abstract Car addCar(Car car);

    public abstract void sort();

    public Car pickUpCar(Car car) {
        for (int i = 0; i < CommonData.packingLotList.size(); i++) {
            ParkingLot parkingLot = CommonData.packingLotList.get(i);
            if (parkingLot.getId() == car.getCarTicket().getParkingLotId() &&
                    isSpecificCar(car.getCarTicket().getCode(), parkingLot.getCarSet())) {
                parkingLot.getCarSet().remove(car);
                CommonData.packingLotList.set(i, parkingLot);
                CommonData.carNumberSet.remove(car.getCarNumber());
                return car;
            }
        }
        return null;
    }

    void parkingDetail(int index, ParkingLot parkingLot, Car car) {
        CommonData.carNumberSet.add(car.getCarNumber());
        CarTicket carTicket = new CarTicket();
        carTicket.setParkingLotId(parkingLot.getId());
        carTicket.setCode(UUID.randomUUID().toString());
        car.setCarTicket(carTicket);
        parkingLot.getCarSet().add(car);
        CommonData.packingLotList.set(index, parkingLot);
    }

    /**
     * 判断车牌是否存在
     *
     * @param carNumber
     * @return
     */
    boolean isExist(String carNumber) {
        if (CommonData.carNumberSet.contains(carNumber)) {
            return true;
        }
        return false;
    }

    /**
     * 凭验证码取车
     *
     * @param code
     * @param carSet
     * @return
     */
    private boolean isSpecificCar(String code, Set<Car> carSet) {
        for (Car car : carSet) {
            if (car.getCarTicket().getCode().equals(code)) {
                return true;
            }
        }
        return false;
    }

    public void initPackingLot() {
        if (CommonData.packingLotList.size() != CommonData.PARKING_LOT_MAX_NUM) {
            for (int i = 0; i < CommonData.PARKING_LOT_MAX_NUM; i++) {
                Set<Car> carSet = new HashSet<>();
                ParkingLot packingLot = new ParkingLot();
                packingLot.setId(i);
                packingLot.setCarSet(carSet);
                packingLot.setMaxSpace(CommonData.MAX_SPACE);
                CommonData.packingLotList.add(packingLot);
            }
        }
    }
}
